package com.bihu.bihudemo.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/*
 * 验证码控制器
 */
@Controller
public class CapcharController {
    public static final String KAPSessionkey = "kap_key";
    @Autowired
    Producer producer;

    @GetMapping("/cap")
    public void  code(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //生成验证码
        String code = producer.createText();
        //验证码存到session中
        request.getSession().setAttribute(KAPSessionkey, code);
        BufferedImage image = producer.createImage(code);
        response.setHeader("Cache-Control", "no-store");
        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "jpeg", outputStream);
    }
}
